<?php
namespace Health\Http\Controllers\Admin;

use Health\Http\Controllers\Admin\BaseController;

use Health\Models\Category;
use Health\Models\Goods;
use Auth;
use Health\Http\Requests\CategoryRequest;

class CategoryController extends BaseController
{
    public function index()
    {
        $data['data']=Category::orderBy('status','desc')->orderBy('sort','desc')->paginate(10);
        return view('admin.category.index',$data);
    }

    public function add()
    {
        return view('admin.category.edit');
    }

    public function edit($id)
    {
        $data['data']=Category::find($id);
        return view('admin.category.edit',$data);
    }

    public function postEdit(CategoryRequest $request)
    {
        $data=array_map('trim', $request->only(['id','category_name', 'status','sort']));
        Category::updateOrCreate(['id'=>$data['id']],$data);
        return redirect('/category');

    }

    public function delete($id)
    {
        if(Goods::where('goods_category_id',$id)->first()){
            return redirect('/category')->withErrors(['category' => '失败咯~,分类下有商品,不能删除']);
        }
        Category::where(['id'=>$id])->delete();
        return redirect('/category');


    }
}